//index.js
const app = getApp()
var db = wx.cloud.database()
Page({
    data: {
        avatarUrl: './user-unlogin.png',
        userInfo: {},
        logged: false,
        takeSession: false,
        requestResult: ''
    },
    // 删除用户记录
    deleteuser: function() {
        db.collection('todos').doc('W5nAPeZP2AO8DuJj').remove({
            success: function (res) {
                
                console.log(res.data)
            }
        })
    },
    // 修改数据
    change_add:function(){
        db.collection('todos').doc('W5nSshx_YaUojGRO').update({
            // data 传入需要局部更新的数据
            data: {
                description: "王一超"
            },
            success: function (res) {
                console.log(res)
            }
        })
    },
    
    // 拿到存储的东西
    getoarcal: function(e) {
        const db = wx.cloud.database()
        db.collection('counters').where({
            _openid: this.data.openid,

        }).get({
            success: function(res) {
                console.log(res)
                this.setData({
                    queryResult: JSON.stringify(res.data, null, 2)
                })
            }
        })
    },
    addword: function() {
        const db = wx.cloud.database()
        db.collection('todos').add({
                // data 字段表示需新增的 JSON 数据
                data: {
                    description: "learn cloud database",
                    due: new Date("2018-09-01"),
                    tags: [
                        "cloud",
                        "database"
                    ],
                    location: new db.Geo.Point(123, 15),
                    done: false
                }
            })
            .then(res => {
                console.log(res)
            })
    },
    // 调取添加的记录
    haveadd: function() {
        db.collection('todos').where({
                _openid: 'obK730AwBw4if_cnzVQu-eS4SgOs',
                done: false
            })
            .get({
                success: function(res) {
                    // res.data 是包含以上定义的两条记录的数组
                    console.log(res.data)
                }
            })
    },

    onLoad: function() {
        if (!wx.cloud) {
            wx.redirectTo({
                url: '../chooseLib/chooseLib',
            })
            return
        }

        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            wx.setStorageSync("userInfo", res.userInfo)

                            this.setData({
                                avatarUrl: res.userInfo.avatarUrl,
                                userInfo: res.userInfo
                            })
                        }
                    })
                }
            }
        })
    },

    onGetUserInfo: function(e) {
        if (!this.logged && e.detail.userInfo) {
            this.setData({
                logged: true,
                avatarUrl: e.detail.userInfo.avatarUrl,
                userInfo: e.detail.userInfo
            })
        }
    },

    onGetOpenid: function() {
        // 调用云函数
        wx.cloud.callFunction({
            name: 'login',
            data: {},
            success: res => {
                console.log('[云函数] [login] user openid: ', res.result.openid)
                app.globalData.openid = res.result.openid
                wx.navigateTo({
                    url: '../userConsole/userConsole',
                })
            },
            fail: err => {
                console.error('[云函数] [login] 调用失败', err)
                wx.navigateTo({
                    url: '../deployFunctions/deployFunctions',
                })
            }
        })
    },

    // 上传图片
    doUpload: function() {
        // 选择图片
        wx.chooseImage({
            count: 3,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function(res) {
                console.log(res)
                wx.showLoading({
                    title: '上传中',
                })

                const filePath = res.tempFilePaths[0]
                console.log(filePath)
                let date = new Date();
                let h = date.getHours();
                let m = date.getMinutes();
                let s = date.getSeconds();

                // 上传图片
                const cloudPath = h + m + s + 'my-image' + filePath.match(/\.[^.]+?$/)[0]

                console.log(cloudPath)
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath,
                    success: res => {
                        console.log('[上传文件] 成功：', res)

                        app.globalData.fileID = res.fileID
                        app.globalData.cloudPath = cloudPath
                        app.globalData.imagePath = filePath

                        wx.navigateTo({
                            url: '../storageConsole/storageConsole'
                        })
                    },
                    fail: e => {
                        console.error('[上传文件] 失败：', e)
                        wx.showToast({
                            icon: 'none',
                            title: '上传失败',
                        })
                    },
                    complete: () => {
                        wx.hideLoading()
                    }
                })

            },
            fail: e => {
                console.error(e)
            }
        })
    },

})